package com.xm.servlet.background.admin;

import com.xm.service.background.AdministratorService;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 后台账号Servlet
 *
 * @author 康文程
 */
@WebServlet("/background/account")
public class AccountServlet extends HttpServlet {
    private final AdministratorService service = new AdministratorService();

    /**
     * @param req  an {@link HttpServletRequest} object that
     *             contains the request the client has made
     *             of the servlet
     * @param resp an {@link HttpServletResponse} object that
     *             contains the response the servlet sends
     *             to the client
     */
    @SneakyThrows(Exception.class)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        // 获取参数
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        //查询账号是否存在
        boolean isLogin = service.isExistenceAdministrator(id, password);
        //判断
        if (isLogin) {
            //生成令牌
            String csrfToken = UUID.randomUUID().toString();

            System.out.println(csrfToken);
            HttpSession scope = req.getSession();
            // 令牌时效时间 8个小时
            scope.setMaxInactiveInterval(60 * 60 * 8);
            //存令牌和账号
            scope.setAttribute("csrfToken", csrfToken);
            scope.setAttribute("id",id);
        } else {
            //失败
            resp.getWriter().println(false);
            System.out.println("用户账号密码错误");
        }
    }
}
